'use client'
import React, { useState, useEffect } from 'react';
import './index.scss';
import { LeftSquareOutlined, PlusCircleOutlined, RightSquareOutlined, EditOutlined, NodeIndexOutlined } from '@ant-design/icons';
import { Button, Popover, message } from 'antd'
import { useRouter } from 'next/navigation';
import UpdataName from "@/app/components/UpdataName/page";
import KeyStore from '@/app/store/key';
import Active from '@/app/store/active'
import Agent from '@/app/store/agent';
import { getConversation, DeleteConversations } from '@/app/api/agent-key/index'
import Cookies from 'js-cookie';

interface SideruiProps {
    width: any,
    setDate: (width: string) => void;
}

const Siderui: React.FC<SideruiProps> = ({ width, setDate }) => {

    const { key, user, setconversation_id, setisdoc, isdoc } = KeyStore()
    const { count, company_img, getDevice, setOpen } = Active()

    const [messagelist, setmessagelist] = useState([])
    const [visible, setvisible] = useState(false)
    const [info, setInfo] = useState({})
    const router = useRouter();
    const [pathid, setpathid] = useState('')
    const [active, setactive] = useState(-1)

    useEffect(() => {
        getmessagelist()

    }, [count, user])

    const getmessagelist = () => {
        if (user == '') return
        getConversation(user, '', 20, key).then((res) => {
            if (res.data.length != 0) {
                setmessagelist(res.data)
            } else {
                setmessagelist([])
            }
            if (typeof window !== 'undefined') {
                console.log(window.location.pathname.split('/pages/agent/')[1]);

                setpathid(window.location.pathname.split('/pages/agent/')[1])
            }
        })
    }

    const setMove = () => {
        const innerwidth = width == '240px' ? '80px' : '240px'
        setDate(innerwidth)
    }


    const handleClick = (index: any) => {
        setactive(index)
        setpathid('-1')
        setOpen(false)
    }

    const Uploca = (name: string = '新对话') => {
        localStorage.setItem('Talk', JSON.stringify({
            created_at: 0,
            id: "",
            inputs: {},
            introduction: null,
            name: name,
            status: "0",
            updated_at: 0,
        }))
    }

    return (
        <div className='sider' style={{ width }}>
            {
                width == '240px' ? <>
                    <div className='sider_top'>
                        <div className='title'>
                            <img src={company_img} alt="" width={150} height={50} onClick={() => { handleClick(-1); router.push('/pages/home') }} />
                            {getDevice() == 'computer' && <LeftSquareOutlined onClick={() => { setMove() }} />}
                        </div>
                        <Button className='button' type="text" icon={<PlusCircleOutlined />} onClick={() => {
                            Uploca()
                            handleClick(-1)
                            setconversation_id('')
                            setisdoc(false)
                            router.push('/pages/home')
                        }}>
                            开启新对话
                        </Button>
                        <div className='agentlist'>
                            <div className='agentitem' onClick={() => {
                                Uploca('公文写作')
                                handleClick(-1)
                                setconversation_id('')
                                router.push('/pages/agent/1')
                                setisdoc(true)
                            }}>
                                <EditOutlined />&nbsp; 公文写作
                            </div>
                            <div className='agentitem' onClick={() => {
                                Uploca('旅游路线')
                                handleClick(-1)
                                setconversation_id('')
                                router.push('/pages/mapagent/1')
                                setisdoc(false)
                            }}>
                                <NodeIndexOutlined />&nbsp; 旅游路线
                            </div>
                        </div>
                        <div className='messagelist'>
                            {
                                messagelist.map((item: any, index) => {
                                    return <div
                                        className={`messageitem ${active === index ? 'active' : pathid == item.id ? 'active' : pathid == '1' && index == 0 && !isdoc ? 'active' : ''}`}
                                        key={item.id}
                                        onClick={(e) => {
                                            e?.stopPropagation()
                                            handleClick(index)
                                            setisdoc(false)
                                            localStorage.setItem('Talk', JSON.stringify(item))
                                            router.push('/pages/agent/' + item.id)
                                        }}>
                                        <span className='txt'>{item.name}</span>
                                        <div className='drop' onClick={(e) => { e?.stopPropagation() }}>
                                            <Popover placement="right" trigger="click" content={<>
                                                <div style={{ cursor: 'pointer', fontSize: '13px' }}>
                                                    <div onClick={(e) => {
                                                        e.stopPropagation();
                                                        setvisible(true)
                                                        setInfo(item)
                                                    }}>重命名</div>
                                                    <div onClick={(e) => {
                                                        DeleteConversations(item.id, { user }, key).then((res: any) => {
                                                            message.success('删除成功')
                                                            handleClick(-1)
                                                            router.push('/pages/home')
                                                            getmessagelist()
                                                        }).catch(err => {
                                                            message.error('删除失败')
                                                        })
                                                    }}>删除</div>
                                                </div>
                                            </>}>...</Popover>
                                        </div>
                                    </div>
                                })
                            }
                        </div>
                    </div>
                    <div className='sider_buttom'>
                        <Button onClick={() => {
                            handleClick(-1)
                            Cookies.remove('access_token', { path: '/' });
                            router.push('/pages/login')
                            if (typeof window !== 'undefined') {
                                localStorage.removeItem('access_token');
                                localStorage.removeItem('refresh_token');
                                localStorage.removeItem('key-store')
                            }
                            message.success('退出成功')
                        }}>退出登录</Button>
                    </div>
                </> :
                    <>
                        <div className='minsider'>
                            <div className='minsider_top'>
                                <div className='company_img'
                                    onClick={() => setMove()}  >
                                    <img src={company_img} alt="" onClick={() => { handleClick; router.push('/pages/home') }} />
                                </div>
                                <RightSquareOutlined
                                    onClick={() => setMove()} />
                                <PlusCircleOutlined onClick={() => {
                                    setactive(-1)
                                    setpathid('-1')
                                    router.push('/pages/home')
                                }} />
                            </div>

                        </div>
                    </>
            }
            <UpdataName info={info} visible={visible} setData={(value) => {
                setvisible(value)
                getmessagelist()
            }} />
        </div>
    );
}
export default Siderui;